// 进行路由权限的处理
import router from '@/router'
// 导入vuex
import store from '@/store'
// console.log(store.getters.token)

// 导入进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// 导入路由规则
import { varRouter } from '@/router'

// 定义白名单
const whiteList = ['/404', '/login']
// 路由前置守卫
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    // 有token
    // 获取用户资料
    if (!store.getters.userInfo.id) {
      const userId = await store.dispatch('user/getUserInfoo')
      // console.log(userId.roles.menus)
      // console.log(varRouter)varRouter
      const flterRouter = varRouter.filter(item => {
        // console.log(item)
        return userId.roles.menus.some(menus => {
          return menus === item.name
        })
      })
      // console.log(flterRouter)
      // 动态追加路由规则,会累积追加，所以退出登录后要清空路由规则
      router.addRoutes([...flterRouter, { path: '*', redirect: '/404', hidden: true }])

      next(to.path)
      // 获取的路由到存到vuex中
      store.commit('user/setMenu', flterRouter)
    }

    if (to.path === '/login') {
      // 进主页
      next('/')
    } else {
      next()
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) === -1) {
      next('/login')
    } else {
      next()
    }
  }
  NProgress.done()
})

router.afterEach(() => {
  NProgress.done()
})
